﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NewtonsoftJsonEx;
using System.IO;

namespace MyEditor 
{

    public class MainSceneEditorWindow : EditorWindow
    {

        [MenuItem("MyEditor/剧情编辑器")]
        public static void InitScene()
        {
            var win = GetWindow<MainSceneEditorWindow>();
            win.titleContent = new GUIContent("剧情编辑器");
            SceneView.duringSceneGui += win.OnSceneGUI;
        }

        private void OnDestroy() {
            SceneView.duringSceneGui -= OnSceneGUI;

            if (mData == null)
            {
                return;
            }

            //检测当前是否有保存
            bool isSave = false;
            if (string.IsNullOrEmpty(mLastSaveStr) == false)
            {
                var curStr = Newtonsoft.Json.JsonConvert.SerializeObject(mData, new JsonSerializerSettings());
                if (mLastSaveStr.Equals(curStr) == false)
                {
                    isSave = true;
                }
            }
            if (isSave)
            {
                return;
            }
            MessageShow.ShowBox("本次修改未保存，是否需要保存",()=> {
                this.SaveData();
            },()=> { });
        }

        #region 当前数据
        /// <summary>
        /// 窗口工具
        /// </summary>
        /// <returns></returns>
        public WindowTools tools = new WindowTools(); 

        /// <summary>
        /// 默认保存路径
        /// </summary>
        public string SavePath = "Assets/ConfigsFile/SceneConfig";  

        /// <summary>
        ///当前保存文件名
        /// </summary>
        public string curFileName = "";  

        /// <summary>
        /// 最后一次保存数据(可以用来做撤回)
        /// </summary>
        private string mLastSaveStr = string.Empty;

        /// <summary>
        /// 场景数据
        /// </summary>
        public SceneData mData;

        /// <summary>
        /// 编辑器当前面板使用参数(不保存，但是当前需要动态改)
        /// </summary>
        private class CurEditorInfo
        {
            public int startIdx;
            public int endIdx;
            public float playSpeed;
        }
        /// <summary>
        /// 编辑器当前面板使用参数
        /// </summary>
        private CurEditorInfo curEditorInfo;

        //--- 面板控件信息
        Vector2 scrollPos_MainPanel;
        int selectIdxMainPanel;

        Vector2 scrollPos_ChapterPanel;
        int selectIdxChapter;

        Vector2 scrollPos_DialoguePanel;
        int selectIdxDialogue;
        #endregion


        private void OnSceneGUI(SceneView view) 
        {   
           
        }
        private void OnGUI() 
        {
            #region 顶部栏按钮
            GUILayout.BeginVertical();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("新建数据",tools.SetGUIOption80_40()))
            {
                if (mData != null)
                {
                    mData = null;
                    curEditorInfo = null;
                }
                curEditorInfo = new CurEditorInfo();
                mData = new SceneData();
            }
            GUILayout.Space(10);
            if (GUILayout.Button("导入数据",tools.SetGUIOption80_40()))
            {
                this.ImportData();
            }
            if (mData == null)
            {
                return;
            }
            GUILayout.Space(10);
            if (GUILayout.Button("保存数据",tools.SetGUIOption80_40()))
            {
                this.SaveData();
            }

            GUILayout.EndHorizontal();

            #region 文件名
            GUILayout.BeginHorizontal();
            string path = "";
            if (string.IsNullOrEmpty(curFileName) == false)
            {
                path = curFileName;
            }
            GUILayout.Label(string.Format("文件路径：{0}", path));
           GUILayout.EndHorizontal();
            #endregion

            GUILayout.EndVertical();
            #endregion

            #region 下方编辑面板
            BeginWindows();
            //左侧剧情编辑列表

            GUILayout.Window(1, new Rect(10, 100, 250, 600), DrawMainInfoPanel, "主面板信息");
            GUILayout.Window(2, new Rect(300,100,150, 600), DrawSmallChapterPanel, "小章节面板");
            GUILayout.Window(3, new Rect(500, 100,800, 600), DrawMainDialoguePanel, "小章节面板");

            EndWindows();
            #endregion

            //if (GUI.changed)
            //{
            //    SceneView.RepaintAll();
            //}
        }

        #region 不同区域的面板绘制
        /// <summary>
        /// 剧情主信息面板
        /// </summary>
        void DrawMainInfoPanel(int winId)
        {
            if (mData == null)
            {
                return;
            }
            EditorGUILayout.BeginVertical();

            #region 顶部按钮
            mData.name = EditorGUILayout.TextField("故事名称：",mData.name);
            mData.playSpeed = EditorGUILayout.FloatField("播放速度：", mData.playSpeed);

            if (mData.listChapterDatas == null)
            {
                mData.listChapterDatas = new List<ChapterData>();
                mData.listChapterDatas.Add(new ChapterData());
            }
            if (GUILayout.Button("新增章节", tools.SetGUIOption(80, 20)))
            {
                mData.listChapterDatas.Add(new ChapterData());
            }
            if (GUILayout.Button("删除章节", tools.SetGUIOption(80, 20)))
            {
                if (mData.listChapterDatas.Count > selectIdxMainPanel)
                {
                    Action enterAction = () => {
                        mData.listChapterDatas.RemoveAt(selectIdxMainPanel);
                        if (selectIdxMainPanel >= mData.listChapterDatas.Count )
                        {
                            selectIdxMainPanel = mData.listChapterDatas.Count - 1;
                        }
                    };
                    //如果子章节没有内容则直接删掉
                    var small = mData.listChapterDatas.Count > selectIdxMainPanel ? mData.listChapterDatas[selectIdxMainPanel].listSmallChapters : null;
                    if (small != null)
                    {
                        if (mData.listChapterDatas.Count <=1)
                        {
                            MessageShow.ShowNote("至少要有一个章节");
                            return;
                        }
                        MessageShow.ShowBox("当前编辑有内容，是否确认删除？", () =>
                        {
                            enterAction();
                        }, () => { });
                    }
                    else
                    {
                        enterAction();
                    }
                  
                   
                }
                
            }
            #endregion

            GUILayout.Space(10);

            EditorGUILayout.BeginHorizontal();

            // 左侧
            #region 左侧
            EditorGUILayout.BeginVertical(tools.SetGUIOption(120,450));
            //章节列表滑块
            string[] chapterNames = new string[mData.listChapterDatas.Count];
            for (int i = 0; i < chapterNames.Length; i++)
            { 
                chapterNames[i] = string.Format("第{0}章",i+1);
            }
            scrollPos_MainPanel = GUILayout.BeginScrollView(scrollPos_MainPanel,false,true,tools.SetGUIOption(120,450));
            selectIdxMainPanel = GUILayout.SelectionGrid(selectIdxMainPanel,chapterNames,1,GUILayout.Width(80));
            GUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
            #endregion

            GUILayout.Space(10);
            // 右侧按钮列表
            #region 右侧
            EditorGUILayout.BeginVertical(tools.SetGUIOption(100, 450));
            if (GUILayout.Button("预览全部",tools.SetGUIOption(100,20)))
            {

            }

            if (GUILayout.Button("预览当前章节", tools.SetGUIOption(100, 20)))
            {

            }
            EditorGUILayout.LabelField("预览速度：", tools.SetGUIOption(50, 20));
            curEditorInfo.playSpeed = EditorGUILayout.FloatField(curEditorInfo.playSpeed, tools.SetGUIOption(50, 20));

            EditorGUILayout.LabelField("开始：", tools.SetGUIOption(50, 20));
            curEditorInfo.startIdx = EditorGUILayout.IntField(curEditorInfo.startIdx, tools.SetGUIOption(50,20));

            EditorGUILayout.LabelField("结束：", tools.SetGUIOption(50, 20));
            curEditorInfo.endIdx = EditorGUILayout.IntField(curEditorInfo.endIdx, tools.SetGUIOption(50, 20));
            if (GUILayout.Button("预览范围内章节", tools.SetGUIOption(100, 20)))
            {

            }
    
            GUILayout.EndVertical();
            #endregion

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();
        }

        /// <summary>
        /// 小章节列表
        /// </summary>
        /// <param name="winId"></param>
        void DrawSmallChapterPanel(int winId)
        {
            if (mData.listChapterDatas == null || mData.listChapterDatas.Count <= 0)
            {
                return;
            }

            EditorGUILayout.BeginVertical();

            // 顶部增删按钮 以及其他
            #region 顶部栏
            EditorGUILayout.BeginVertical();
            if (mData.listChapterDatas[selectIdxMainPanel].listSmallChapters == null)
            {
                mData.listChapterDatas[selectIdxMainPanel].listSmallChapters = new List<SmallChapter>();
                mData.listChapterDatas[selectIdxMainPanel].listSmallChapters.Add(new SmallChapter());
            }

            if (GUILayout.Button("新增小节",tools.SetGUIOption(80,20)))
            {
                mData.listChapterDatas[selectIdxMainPanel].listSmallChapters.Add(new SmallChapter());
            }
            if (GUILayout.Button("删除小节", tools.SetGUIOption(80,20)))
            {
                if (mData.listChapterDatas[selectIdxMainPanel].listSmallChapters.Count > selectIdxChapter)
                {
                    if (mData.listChapterDatas[selectIdxMainPanel].listSmallChapters.Count <=1)
                    {
                        MessageShow.ShowNote("至少要有一个小节");
                        return;
                    }
                    mData.listChapterDatas[selectIdxMainPanel].listSmallChapters.RemoveAt(selectIdxChapter);
                }
            }

            EditorGUILayout.EndVertical();
            #endregion

            // 小章节滑动列表
            #region 小章节
            EditorGUILayout.BeginVertical();

            var listChapter = mData.listChapterDatas[selectIdxMainPanel].listSmallChapters;

            string[] chapterNames = new string[listChapter.Count];
            for (int i = 0; i < chapterNames.Length; i++)
            {
                chapterNames[i] = string.Format("{0}-{1}", selectIdxMainPanel+1, i + 1);
            }
            scrollPos_ChapterPanel = GUILayout.BeginScrollView(scrollPos_ChapterPanel, false, true, tools.SetGUIOption(120, 500));
            selectIdxChapter = GUILayout.SelectionGrid(selectIdxChapter, chapterNames, 1, GUILayout.Width(80));
            GUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
            #endregion

            EditorGUILayout.EndVertical();

        }

        /// <summary>
        /// 对话主面板
        /// </summary>
        void DrawMainDialoguePanel(int winId)
        {
            if (mData.listChapterDatas.Count <= 0)
            {
                return;
            }
            var chapterData = mData.listChapterDatas[selectIdxMainPanel];
            if (chapterData.listSmallChapters.Count <= 0)
            {
                return;
            }
            var smallChapters = chapterData.listSmallChapters[selectIdxChapter];
            if (smallChapters.listDialogueBases == null)
            {
                chapterData.listSmallChapters[selectIdxChapter].listDialogueBases = new List<DialogueBase>();
            }
           
            string[] dialogueNames = new string[smallChapters.listDialogueBases.Count];
            for (int i = 0; i < dialogueNames.Length; i++)
            {
                dialogueNames[i] = string.Format("{0}{1}-{2}-{3}", smallChapters.listDialogueBases[i].GetDialogueName(), selectIdxMainPanel, selectIdxChapter,i);
            }

            EditorGUILayout.BeginHorizontal();

            //左侧列表
            #region
            EditorGUILayout.BeginVertical(tools.SetGUIOption(200,500));
            scrollPos_DialoguePanel = GUILayout.BeginScrollView(scrollPos_DialoguePanel, false, true, tools.SetGUIOption(180, 500));
            selectIdxDialogue = GUILayout.SelectionGrid(selectIdxDialogue, dialogueNames, 1, GUILayout.Width(170));
            GUILayout.EndScrollView();

            EditorGUILayout.EndVertical();
            #endregion

            //右侧面板
            #region
            EditorGUILayout.BeginVertical(tools.SetGUIOption(600, 500));


            EditorGUILayout.EndVertical();
            #endregion

 
            EditorGUILayout.EndHorizontal();

            //底部按钮
            GUILayout.Space(10);
            #region
            EditorGUILayout.BeginVertical();
            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button("新建剧情对话", tools.SetGUIOption(80, 20)))
            {

            }



            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
            #endregion

        }

        #endregion



        #region 当前方法
        /// <summary>
        /// 保存数据
        /// </summary>
        private void SaveData()
        {
            string name = string.IsNullOrEmpty(curFileName)? "scene":curFileName;
            string path = EditorUtility.SaveFilePanel("选择保存路径",SavePath,name,"editor.json");
            if (path.Length != 0)
            {
                string savePath = path.Substring(path.IndexOf("Assets"));
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(mData,new JsonSerializerSettings());
                File.WriteAllText(savePath,jsonStr);
                mLastSaveStr = jsonStr;
                MessageShow.ShowNote("保存完成");
                curFileName = Path.GetFileName(savePath);
            }
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        private void ImportData()
        {
            string path = EditorUtility.OpenFilePanel("选择数据文件", SavePath, "editor.json");
            string str = File.ReadAllText(path);
            mData = Newtonsoft.Json.JsonConvert.DeserializeObject<SceneData>(str);
            curEditorInfo = new CurEditorInfo();
            MessageShow.ShowNote("加载成功");
            mLastSaveStr = str;
            curFileName = Path.GetFileName(path);
           
        }
        #endregion
    }

}

